package com.jzoom.zoom.admin.models;

import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.common.codec.HashStr;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.dao.Record;
import com.jzoom.zoom.token.TokenService;
import org.apache.commons.lang3.StringUtils;

public class AccessService {


    private static final String SALT = "546eb64417dd3e3894e03c6c013d159eVG62RBfdPjiU4DxsAT0Vng==";
    @Inject(value = "admin")
	private Dao dao;

	@Inject
    private TokenService tokenService;


    public String login(String account, String pwd) throws PasswordException, UserNotFoundException {
        Record record = dao.table("sys_user")
                .where("account", account).get();
		if (record == null) {
            throw new UserNotFoundException();
        }

        String id = record.getString("id");
        verifyPwd(id, pwd, record.getString("pwd"));

        // 生成token
        return tokenService.generateToken(record.getString("id"), record.getString("role"));
    }

    private void verifyPwd(String userId, String input, String userPwd) throws PasswordException {
        String encrypted = encrypt(userId, input);
        if (!StringUtils.equals(encrypted, userPwd)) {
            throw new PasswordException();
        }
    }

    public static String encrypt(String userId, String input) {
        return HashStr.sha256(userId + SALT + input);
    }

    public static class PasswordException extends Exception {

    }

    public static class UserNotFoundException extends Exception {

    }

    public void updatePass(String userId,
                           String oldPass,
                           String newPass) throws UserNotFoundException, PasswordException {
        Record record = dao.table("sys_user").select("pwd").where("id", userId).get();
        if (record == null) {
            throw new UserNotFoundException();
        }

        String pwd = record.get("pwd", String.class);

        verifyPwd(userId, oldPass, pwd);

        dao.table("sys_user").where("id", userId).set("pwd", encrypt(userId, newPass)).update();

    }
}
